import { catalogMap } from '@/router/catalog'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
 function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterCatalogs(catalogs, roles) {
  const accessedCatalogs = catalogs.filter(catalog => {
    if (hasPermission(roles, catalog)) {
      return true
    }
    return false
  })
  return accessedCatalogs;
}

const topbar = {
  state: {
    catalog: [],
    activeCatalog: 0,
    topbarIndex: '',
    currentRouteLink: "",
  },
  mutations: {
    SET_CATALOGS: (state, val) => {
      state.catalog = val
    },
    SET_ACTIVE_CATALOG: (state, val) => {
      state.activeCatalog = val
    },
    SET_TOPBAR_INDEX: (state, val) => {
      state.topbarIndex = val

      let arr = state.topbarIndex.split('-');
      try {
        if (arr.length === 3) {
          state.currentRouteLink = state.catalog[state.activeCatalog].menu[parseInt(arr[2])].routeLink;
        } else if (arr.length === 4) {
          state.currentRouteLink = state.catalog[state.activeCatalog].menu[parseInt(arr[2])].submenu[parseInt(arr[3])].routeLink;
        } else {
          state.currentRouteLink = '';
        }
      } catch(err) {
        state.currentRouteLink = '';
      }
    }
  },
  actions: {
    setActiveCatalog({ commit }, val) {
      commit('SET_ACTIVE_CATALOG', val)
    },
    setTopbarIndex({ commit }, val) {
      commit('SET_TOPBAR_INDEX', val)
    },
    GenerateCatalogs({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data
        let accessedCatalogs = filterCatalogs(catalogMap, roles)
        commit('SET_CATALOGS', accessedCatalogs)
        resolve()
      })
    }
  },
}

export default topbar
